﻿using Framework;
using Framework.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Koala.JiraTool.ScheduledTasks
{
    internal class FormLoadEvent : IMainFormEvent
    {
        private readonly IDataPersistence _dataPersistence;
        private readonly ITaskController _taskController;

        public FormLoadEvent(IDataPersistence dataPersistence, ITaskController taskController)
        {
            _dataPersistence = dataPersistence;
            _taskController = taskController;
        }

        #region Implementation of IMainFormEvent

        /// <summary>
        /// 主窗体加载完毕。
        /// </summary>
        public void LoadOk()
        {
            var startSettings = _dataPersistence.Get<ScheduledItemSettings>("sicStart_Settings");
            var stopSettings = _dataPersistence.Get<ScheduledItemSettings>("sicStop_Settings");
            Handle(startSettings, true);
            Handle(stopSettings, false);
        }

        private void Handle(ScheduledItemSettings settings, bool isStart)
        {
            if (settings == null || !settings.StartAutoRun) return;

            var list = _dataPersistence.Get<List<TaskInfo>>(isStart ? "sicStart" : "sicStop" + "_ScheduledItemControl_taskListControl_TaskList");

            if (list == null)
                return;

            var timeSpans = GetRunTimeSpan(settings.Time);
            var nextTime = GetNextTimeSpan(timeSpans);
            if (nextTime.HasValue) return;
            foreach (var taskInfo in list)
            {
                if (isStart)
                    _taskController.StartTask(taskInfo.Id);
                else
                    _taskController.StopTask(taskInfo.Id);
            }
        }

        #endregion Implementation of IMainFormEvent

        private TimeSpan? GetNextTimeSpan(TimeSpan[] timeSpans)
        {
            if (!timeSpans.Any())
            {
                return null;
            }
            var time = timeSpans.First();
            var dayTime = DateTime.Now.TimeOfDay;
            return time.Subtract(new TimeSpan(dayTime.Hours, dayTime.Minutes, dayTime.Seconds));
        }

        private TimeSpan[] GetRunTimeSpan(string time)
        {
            var timeSpans = new List<TimeSpan>();
            var strs = time.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var str in strs)
            {
                TimeSpan result;
                if (TimeSpan.TryParse(str, out result))
                {
                    timeSpans.Add(result);
                }
            }
            var dateTime = DateTime.Now;
            var currentTime = dateTime.TimeOfDay;
            //过滤无法执行到的时间，并排序。
            return timeSpans.Where(model => model > currentTime).OrderBy(model => model.TotalMilliseconds).ToArray();
        }
    }
}